﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Security.Cryptography;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.RegularExpressions;
using CoreShop.App;
using CoreShop.Library;
using CoreShop.Services;
using System.Windows.Forms;
using CoreShop.Model;
using CoreShop.PrintService;
using SqlSugar;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Rebar;
using Yitter.IdGenerator;
using SqlSugar.Extensions;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using Sunny.UI;
using System.Xml;
using NPOI.SS.Formula.Functions;
using NPOI.Util;
using WebKit.DOM;
using static CoreShop.Library.GlobalEnumVars;
using System.Windows.Forms.VisualStyles;
using static CoreShop.App.ActivitieUtil;

namespace CoreShop.App
{
    public class ProcessUtil
    {       

        /// <summary>
        /// Url初始化
        /// </summary>
        public static void SetWebUrlInit()
        {
            try
            {
                var systemsetup = new corecmssystemsetupService().SelectDataFirst();
                string mApiUrl = IniFiles.ReadIniData("WebAPI", "adminApiUrl");
                if (systemsetup != null)
                {
                    if (mApiUrl != null) systemsetup.adminApiUrl = mApiUrl;
                    mApiUrl = IniFiles.ReadIniData("WebAPI", "corehubUrl");
                    if (mApiUrl != null) systemsetup.corehubUrl = mApiUrl;
                    mApiUrl = IniFiles.ReadIniData("WebAPI", "carouselUrl");
                    if (mApiUrl != null) systemsetup.carouselUrl = mApiUrl;
                    var bl = new corecmssystemsetupService().Update(systemsetup);
                    AppConstVars.sUrl = systemsetup.adminApiUrl;
                }
            }
            catch (Exception ex)
            {
            }
        }

        /// <summary>
        /// 系统初始化
        /// </summary>
        public static void SetSystemInit()
        {
            #region 打印机
            int printscheme_id = CommFunc.ConvertToInt32(IniFiles.ReadIniData("SystemPara", "printscheme_id"));
            var printscheme = new corecmsprintschemeServices().GetById(printscheme_id);
            if (printscheme == null)
            {
                printscheme = new corecmsprintscheme()
                {
                    printerType = (int)GlobalEnumVars.printerType.PosBill,
                    sendPrintWay = (int)GlobalEnumVars.SendPrintWay.Drive,
                    gearName = "前台收银",
                    printerName = "默认打印机",
                    region = "前台收银",
                    printerIP = "127.0.0.1",
                    defaultFlag = true,
                };
                var frm = new frmPrintSchemeInfo(printscheme);
                frm.ShowDialog();
                frm.Dispose();
            }
            #endregion
        }

        public static corecmsuser GetMembers(string sNumber, int iTag, Form form)
        {
            corecmsuser member = null;
            var where = Expressionable.Create<corecmsuser>();
            where = where.And(p => p.mobile.Contains(sNumber) || p.number.Contains(sNumber) || p.userName.Contains(sNumber));
            where = where.And(p => p.status == 1);
            if (iTag == 1)
            {
                member = new corecmsuserServices().SelectUserById(CommFunc.ConvertToInt64(sNumber));
            }
            else
            {
                List<corecmsuser> memberList = new corecmsuserServices().GetList(where.ToExpression());
                if (memberList.Count == 1)
                {
                    member = memberList.First();
                }
                else if (memberList.Count > 1)
                {
                    FrmUser theForm = new FrmUser(sNumber, true);
                    theForm.Owner = form;
                    if (theForm.ShowDialog() == System.Windows.Forms.DialogResult.Yes)
                    {
                        member = theForm.member_sel;
                    }
                    theForm.Dispose();
                }
                if (member != null)
                {
                    corecmsusergrade memberGrade = new corecmsusergradeServices().GetById(member.grade);
                    member.discountValue = 100;
                    if (memberGrade != null) member.discountValue = memberGrade.discountValue;
                }
            }
            return member;
        }

        /// <summary>
        /// 获取系统参数
        /// </summary>
        public static void GetSystemPara()
        {
            GetSystemSetup();
            GetIniParaSetup();
            GetSystemPayment();
            AppConstVars.sysStore = new corecmsstoreServices().GetById(AppConstVars.sysUser.storeId);
            AppConstVars.sysUserRole = GetUserRolePos(AppConstVars.sysUser.id);//获取前台权限
            AppConstVars.sysUserRoleInfo = GetUserRoleInfo(CommFunc.ConvertToInt64(AppConstVars.sysUser.posRoleId));
            AppConstVars.payaccount = new corecmspayaccountServices().GetFirst(p => p.status == true);
        }

        /// <summary>
        /// 获取系统参数
        /// </summary>
        public static void GetSystemPayment()
        {
            AppConstVars.sysPayments = new corecmspaymentsService().AsQueryable()
                .Where(p => p.storeId == AppConstVars.sysUser.storeId && p.isEnable == true || p.storeId == 0).OrderBy(p=>p.sort).ToList();
        }

        /// <summary>
        /// 本地打印方案
        /// </summary>
        public static void GetIniParaSetup()
        {
            AppConstVars.mCashBoxType = CommFunc.ConvertToInt32(IniFiles.ReadIniData("Local", "CashBoxType"));
            AppConstVars.mCashBoxPort = EnumHelper.GetDescByValue<GlobalEnumVars.CashBoxType>(AppConstVars.mCashBoxType);
            AppConstVars.mWeighMode = CommFunc.ConvertToInt32(IniFiles.ReadIniData("Weight", "WeighMode"));
            AppConstVars.mConvert = CommFunc.ConvertToInt32(IniFiles.ReadIniData("Weight", "Convert")) + 1;
            AppConstVars.mScaleType = CommFunc.ConvertToInt32(IniFiles.ReadIniData("Weight", "ScaleType"));
            AppConstVars.mReadType = CommFunc.ConvertToInt32(IniFiles.ReadIniData("Weight", "ReadType"));
        }

        /// <summary>
        /// 清一些多余的历史数据
        /// </summary>
        public static void ClearHistoryData(corecmsstore store)
        {
            try
            {
                var where = Expressionable.Create<corecmsdiscountrules>();
                where = where.And(p => p.status != (int)GlobalEnumVars.DiscountStatus.IsCheck);
                where = where.And(p => p.endTime < DateTime.Now);
                bool returnValue = new corecmsdiscountrulesServices().Delete(where.ToExpression());

                new corecmsprinttasklogServices().Delete(p=>p.createTime < DateTime.Now.AddDays(-30));

                //清理促销数据
                var where1 = Expressionable.Create<activitymaster>();
                where1 = where1.And(p => p.status == (int)GlobalEnumVars.ActivityStatus.Stop);//审核状态
                where1 = where1.And(p => p.activityEndDate < DateTime.Now);//有效期范围
                var activityIds = new activitymasterServices().AsQueryable().Where(where1.ToExpression()).Select(p=>p.activityInfoId).ToList();
                if (activityIds.Count > 0) 
                { 
                
                }
            }
            catch
            {

            }
        }

        /// <summary>
        /// 获取单据编码
        /// </summary>
        public static string GetNumberBill(int type)
        {
            string str;
            switch (type)
            {
                case (int)GlobalEnumVars.SerialNumberType.交班单号:
                    str = type + YitIdHelper.NextId().ToString();
                    break;
                case (int)GlobalEnumVars.SerialNumberType.零售单号:
                    str = type + YitIdHelper.NextId().ToString();
                    break;
                default:
                    str = DateTime.Now.ToString("yyyyMMddHHssmmfff");
                    break;
            }
            return str;
        }

        public static void SetNumberPos()
        {
            //if (numberModel.numberDate.ToString("yyyyMMdd").ObjToInt(0) != DateTime.Now.ToString("yyyyMMdd").ObjToInt(1))
            //{
            //    numberModel.numberDate = DateTime.Now;
            //    numberModel.lastNumber = 0;
            //    numberDetail.Update(numberModel);
            //}
            //numberModel.numberDate = DateTime.Now;
            //numberModel.lastNumber += 1;
            //numberDetail.Update(numberModel);
        }

        /// <summary>
        /// 获取单据编码
        /// </summary>
        public static string GetOrderNo(int serialNumberType)
        {
            string str = "";
            string sNumber;
            var numberDetail = new corecmsnumberdetailService();
            var numberModel = numberDetail.SelectDataById(serialNumberType);
            switch (AppConstVars.systemsetup.billNumberFirst)
            {
                case (int)GlobalEnumVars.BillNumberFirst.ByClass://每班编号（空值）
                    #region
                    if (CommFunc.ConvertToBigInt(numberModel.classId) != AppConstVars.classId)
                    {
                        numberModel.classId = AppConstVars.classId;
                        numberModel.numberDate = DateTime.Now;
                        numberModel.lastNumber = 1;
                    }
                    else
                        numberModel.lastNumber += 1;
                    numberDetail.Update(numberModel);
                    sNumber = numberModel.lastNumber.ToString();
                    str = DateTime.Now.ToString("yyyyMMddHHmmss") + AppConstVars.sysStore.corpId.ToString() + sNumber.PadLeft(AppConstVars.systemsetup.billNumberLast, '0');
                    #endregion
                    break;
                case (int)GlobalEnumVars.BillNumberFirst.ByDate://每日编号（空值）
                    #region
                    if (numberModel.numberDate.ToString("yyyyMMdd").ObjToInt(0) != DateTime.Now.ToString("yyyyMMdd").ObjToInt(1))
                    {
                        numberModel.numberDate = DateTime.Now;
                        numberModel.lastNumber = 1;
                    }
                    else
                        numberModel.lastNumber += 1;
                    numberDetail.Update(numberModel);
                    sNumber = numberModel.lastNumber.ToString();
                    str = DateTime.Now.ToString("yyyyMMddHHmmss") + AppConstVars.sysStore.corpId.ToString() + sNumber.PadLeft(AppConstVars.systemsetup.billNumberLast, '0');
                    #endregion
                    break;
                case (int)GlobalEnumVars.BillNumberFirst.ByYYMMDD://短年月日 (如：220212)
                    #region
                    if (numberModel.numberDate.ToString("yyyyMMdd").ObjToInt(0) != DateTime.Now.ToString("yyyyMMdd").ObjToInt(1))
                    {
                        numberModel.numberDate = DateTime.Now;
                        numberModel.lastNumber = 1;
                    }
                    else
                        numberModel.lastNumber += 1;
                    numberDetail.Update(numberModel);
                    sNumber = numberModel.lastNumber.ToString();
                    //str = DateTime.Now.ToString("yyMMddHHssmm") + AppConstVars.sysStore.corpId.ToString() + sNumber.PadLeft(AppConstVars.systemsetup.billNumberLast, '0');
                    str = DateTime.Now.ToString("yyMMddHHmm") + AppConstVars.sysStore.corpId.ToString() + sNumber.PadLeft(AppConstVars.systemsetup.billNumberLast, '0');
                    #endregion                    
                    break;
                case (int)GlobalEnumVars.BillNumberFirst.ByYYMM://短年月 (如：2202)
                    #region
                    if (numberModel.numberDate.ToString("yyyyMM").ObjToInt(0) != DateTime.Now.ToString("yyyyMM").ObjToInt(1))
                    {
                        numberModel.numberDate = DateTime.Now;
                        numberModel.lastNumber = 1;
                    }
                    else
                        numberModel.lastNumber += 1;
                    numberDetail.Update(numberModel);
                    sNumber = numberModel.lastNumber.ToString();
                    str = DateTime.Now.ToString("yyMM") + AppConstVars.sysStore.corpId.ToString() + sNumber.PadLeft(AppConstVars.systemsetup.billNumberLast, '0');
                    #endregion  
                    break;
                case (int)GlobalEnumVars.BillNumberFirst.ByYYYYMMDD://长年月日 (如：20220212)
                    #region
                    if (numberModel.numberDate.ToString("yyyyMMdd").ObjToInt(0) != DateTime.Now.ToString("yyyyMMdd").ObjToInt(1))
                    {
                        numberModel.numberDate = DateTime.Now;
                        numberModel.lastNumber = 1;
                    }
                    else
                        numberModel.lastNumber += 1;
                    numberDetail.Update(numberModel);
                    sNumber = numberModel.lastNumber.ToString();
                    str = DateTime.Now.ToString("yyyyMMddHHmmss") +AppConstVars.sysStore.corpId.ToString() + sNumber.PadLeft(AppConstVars.systemsetup.billNumberLast, '0');
                    #endregion 
                    break;
                case (int)GlobalEnumVars.BillNumberFirst.ByYYYYMM://长年月 (如：202202)
                    #region
                    if (numberModel.numberDate.ToString("yyyyMM").ObjToInt(0) != DateTime.Now.ToString("yyyyMM").ObjToInt(1))
                    {
                        numberModel.numberDate = DateTime.Now;
                        numberModel.lastNumber = 1;
                    }
                    else
                        numberModel.lastNumber += 1;
                    numberDetail.Update(numberModel);
                    sNumber = numberModel.lastNumber.ToString();
                    str = DateTime.Now.ToString("yyyyMMddHHssmm") + sNumber.PadLeft(AppConstVars.systemsetup.billNumberLast, '0');
                    #endregion 
                    break;
                default:
                    str = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                    break;
            }
            return str;
            //return YitIdHelper.NextId().ToString() + str ; 
        }


        /// <summary>
        /// 获取单据编码
        /// </summary>
        public static string GetNumberPos(long classId)
        {
            string str = "";
            string sNumber;
            var numberDetail = new corecmsnumberdetailService();
            var numberModel = numberDetail.SelectDataById((int)GlobalEnumVars.SerialNumberType.零售单号);
            switch (AppConstVars.systemsetup.billNumberFirst)
            {
                case (int)GlobalEnumVars.BillNumberFirst.ByClass://每班编号（空值）
                    #region
                    if (CommFunc.ConvertToBigInt(numberModel.classId) != classId)
                    {
                        numberModel.numberDate = DateTime.Now;
                        numberModel.lastNumber = 1;
                        numberModel.classId = classId;
                    }
                    else
                        numberModel.lastNumber += 1;
                    numberDetail.Update(numberModel);
                    sNumber = numberModel.lastNumber.ToString();
                    str = sNumber.PadLeft(AppConstVars.systemsetup.billNumberLast, '0');
                    #endregion
                    break;
                case (int)GlobalEnumVars.BillNumberFirst.ByDate://每日编号（空值）
                    #region
                    if (numberModel.numberDate.ToString("yyyyMMdd").ObjToInt(0) != DateTime.Now.ToString("yyyyMMdd").ObjToInt(1))
                    {
                        numberModel.numberDate = DateTime.Now;
                        numberModel.lastNumber = 1;
                    }
                    else
                        numberModel.lastNumber += 1;
                    numberDetail.Update(numberModel);
                    sNumber = numberModel.lastNumber.ToString();
                    str = sNumber.PadLeft(AppConstVars.systemsetup.billNumberLast, '0');
                    #endregion
                    break;
                case (int)GlobalEnumVars.BillNumberFirst.ByYYMMDD://短年月日 (如：220212)
                    #region
                    if (numberModel.numberDate.ToString("yyyyMMdd").ObjToInt(0) != DateTime.Now.ToString("yyyyMMdd").ObjToInt(1))
                    {
                        numberModel.numberDate = DateTime.Now;
                        numberModel.lastNumber = 1;
                    }
                    else
                        numberModel.lastNumber += 1;
                    numberDetail.Update(numberModel);
                    sNumber = numberModel.lastNumber.ToString();
                    str = DateTime.Now.ToString("yyMMdd") + sNumber.PadLeft(AppConstVars.systemsetup.billNumberLast, '0');
                    #endregion                    
                    break;
                case (int)GlobalEnumVars.BillNumberFirst.ByYYMM://短年月 (如：2202)
                    #region
                    if (numberModel.numberDate.ToString("yyyyMM").ObjToInt(0) != DateTime.Now.ToString("yyyyMM").ObjToInt(1))
                    {
                        numberModel.numberDate = DateTime.Now;
                        numberModel.lastNumber = 1;
                    }
                    else
                        numberModel.lastNumber += 1;
                    numberDetail.Update(numberModel);
                    sNumber = numberModel.lastNumber.ToString();
                    str = DateTime.Now.ToString("yyMM") + sNumber.PadLeft(AppConstVars.systemsetup.billNumberLast, '0');
                    #endregion  
                    break;
                case (int)GlobalEnumVars.BillNumberFirst.ByYYYYMMDD://长年月日 (如：20220212)
                    #region
                    if (numberModel.numberDate.ToString("yyyyMMdd").ObjToInt(0) != DateTime.Now.ToString("yyyyMMdd").ObjToInt(1))
                    {
                        numberModel.numberDate = DateTime.Now;
                        numberModel.lastNumber = 1;
                    }
                    else
                        numberModel.lastNumber += 1;
                    numberDetail.Update(numberModel);
                    sNumber = numberModel.lastNumber.ToString();
                    str = DateTime.Now.ToString("yyyyMMdd") + sNumber.PadLeft(AppConstVars.systemsetup.billNumberLast, '0');
                    #endregion 
                    break;
                case (int)GlobalEnumVars.BillNumberFirst.ByYYYYMM://长年月 (如：202202)
                    #region
                    if (numberModel.numberDate.ToString("yyyyMM").ObjToInt(0) != DateTime.Now.ToString("yyyyMM").ObjToInt(1))
                    {
                        numberModel.numberDate = DateTime.Now;
                        numberModel.lastNumber = 1;
                    }
                    else
                        numberModel.lastNumber += 1;
                    numberDetail.Update(numberModel);
                    sNumber = numberModel.lastNumber.ToString();
                    str = DateTime.Now.ToString("yyyyMM") + sNumber.PadLeft(AppConstVars.systemsetup.billNumberLast, '0');
                    #endregion 
                    break;
                default:
                    str = DateTime.Now.ToString("yyyyMMddHHssmmfff");
                    break;
            }
            return str;
        }


        /// <summary>
        /// 获取用户权限(是不是没有，没有返回true)
        /// </summary>
        public static bool GetUserRole(GlobalEnumVars.UserRoleType userRole, decimal value)
        {
            if (!GetUserRoleAny(userRole, value))
            {
                UIMessageBox.Show("该用户没有使用该功能的权限。", "提示:", UIStyle.Green, UIMessageBoxButtons.OK);
                return false;
            }
            return true;
        }

        /// <summary>
        /// 获取用户权限
        /// </summary>
        public static bool GetUserRoleAny(GlobalEnumVars.UserRoleType userRole, decimal value, bool isUserRoleMore = true)
        {            
            //最大优惠金额
            if (userRole == GlobalEnumVars.UserRoleType.maxReduceAmount) 
            {
                if ((value > AppConstVars.sysUserRoleInfo.maxDiscountAmount) && (AppConstVars.sysUserRoleInfo.maxDiscountAmount > 0))
                {
                    var moreUserRoleInfo = GetUserRoleInfoMore(userRole);
                    if (moreUserRoleInfo == null) return false;
                    if ((value < moreUserRoleInfo.maxDiscountAmount) && (moreUserRoleInfo.maxDiscountAmount > 0)) return false;
                }
                return true;
            }
            //最大折扣
            if (userRole == GlobalEnumVars.UserRoleType.maxDiscountValue)
            {
                if (value < AppConstVars.sysUserRoleInfo.discountRate * 100)
                {
                    var moreUserRoleInfo = GetUserRoleInfoMore(userRole);
                    if (moreUserRoleInfo == null) return false;
                    if (value < moreUserRoleInfo.discountRate * 100) return false;
                }
                return true;
            }

            var checkUserRole = AppConstVars.sysUserRole.Find(p => p.component == userRole.ToString());
            if (checkUserRole == null) return false;//没有该权限就默认为可用。
            if (checkUserRole.visible && checkUserRole.status) return true;
            if (!isUserRoleMore) return false;
            
            var moreUserRoles = GetUserRoleMore(userRole);
            if (moreUserRoles == null) return false;

            checkUserRole = moreUserRoles.Find(p => p.component == userRole.ToString());
            if ((checkUserRole != null) && checkUserRole.visible && checkUserRole.status) return true;

            return false;
        }

        /// <summary>
        /// 获取用户权限
        /// </summary>
        public static List<sysrolepos> GetUserRoleMore(GlobalEnumVars.UserRoleType userRole)
        {
            List<sysrolepos> moreUserRole = null;
            var frm = new frmGetUserRole(userRole);
            if (frm.ShowDialog() == DialogResult.OK)
            {
                moreUserRole = frm.checkUserRole;
            }
            frm.Dispose();
            return moreUserRole;
        }

        /// <summary>
        /// 获取用户权限
        /// </summary>
        public static sysroleinfo GetUserRoleInfoMore(GlobalEnumVars.UserRoleType userRole)
        {
            sysroleinfo moreUserRole = null;
            var frm = new frmGetUserRole(userRole);
            if (frm.ShowDialog() == DialogResult.OK)
            {
                moreUserRole = frm.checkUserRoleInfo;
            }
            frm.Dispose();
            return moreUserRole;
        }

        /// <summary>
        /// 获取单据编码
        /// </summary>
        public static string GetNumberClass(long classId)
        {
            var numberDetail = new corecmsnumberdetailService();
            var numberModel = numberDetail.SelectDataById((int)GlobalEnumVars.SerialNumberType.交班单号);
            if (numberModel.numberDate.ToString("yyyyMMdd").ObjToInt(0) != DateTime.Now.ToString("yyyyMMdd").ObjToInt(1))
            {
                numberModel.numberDate = DateTime.Now;
                numberModel.lastNumber = 1;
            }
            else
            {
                numberModel.lastNumber += 1;
            }
            numberModel.classId = classId;//corecmsnumberdetail.classId存最后一个交班的ID
            numberDetail.Update(numberModel);

            string sNumber = numberModel.lastNumber.ToString();
            string pnum = sNumber.PadLeft(4, '0');
            string str = DateTime.Now.ToString("yyyyMMddHHssmmfff") + pnum;
            return str;
        }

        #region 根据商品ID生成ordering
        /// <summary>
        /// 根据商品类型ID查询类型名称
        /// </summary>
        /// <param name="custoType"></param>
        /// <returns></returns>
        public static corecmsfoodordering CreateByFoodId(Form form, corecmsfoodorderingmaster orderingMaster,
            long foodId, long specId, decimal dQuantity, corecmsuser member, corecmsemployee employee, ref string msgStr, decimal weight = 0)
        {
            corecmsfood food = new corecmsfoodServices().GetSingle(a => a.id == foodId);
            if (food == null) return null;
            if (food.sellStatus == 0)
            {
                msgStr = "该商品已停售。";
                return null;
            }

            var where = Expressionable.Create<corecmsfoodspec>();
            where = where.And(p => p.foodId == food.id);
            where = where.And(p => p.isDelete == false);
            where = where.And(p => p.onLine == true);
            if (specId > 0)
                where = where.And(p => p.id == specId);        

            var specList = new corecmsfoodspecServices().AsQueryable().WhereIF(true, where.ToExpression()).With(SqlWith.NoLock).ToList();
            if ((specList == null) || (specList.Count == 0)) return null;

            var foodspec = specList.FirstOrDefault();

            #region 获取商品规格
            if (specList.Count > 1)
            {
                foodspec = null;
                var frm = new frmFoodSpecSelect(specList, food, true);
                if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    foodspec = frm.specModel;
                }
                frm.Dispose();
                if (foodspec == null) return null;
            }
            specId = foodspec.id;
            #endregion

            corecmsfoodordering ordering = null;
            var foodorderingSrv = new corecmsfoodorderingServices();
            if ((AppConstVars.systemsetup.mergeOrderItem) && (foodspec.weighType != (int)GlobalEnumVars.WeighType.Weigh))
            {
                var where1 = Expressionable.Create<corecmsfoodordering>();
                where1 = where1.And(p => p.orderId == orderingMaster.orderId);
                where1 = where1.And(p => p.foodId == foodId && p.foodSpecId == specId);
                where1 = where1.And(p => p.dataType != (int)GlobalEnumVars.OrderingDataType.Present);
                where1 = where1.And(p => p.dataType != (int)GlobalEnumVars.OrderingDataType.ActivityDis);
                where1 = where1.And(p => p.dataType != (int)GlobalEnumVars.OrderingDataType.ActivityGift);
                var orderingOrgList = foodorderingSrv.AsQueryable().WhereIF(true, where1.ToExpression()).With(SqlWith.NoLock).ToList();
                if ((orderingOrgList != null) && (orderingOrgList.Count > 0))
                {
                    ordering = orderingOrgList.FirstOrDefault();
                    dQuantity  += ordering.quantity;
                }
            }
            if (ordering == null)
            {
                ordering = foodorderingSrv.CreateByFoodId(foodspec.id, dQuantity, 0);
                if (ordering == null) return ordering;
                #region 称重商品称数量
                //if ((food.stand == (int)GlobalEnumVars.stand.Weigh) && (foodspec.weighType == (int)GlobalEnumVars.WeighType.Weigh))
                if ((food.stand != (int)GlobalEnumVars.stand.Count) && (foodspec.weighType == (int)GlobalEnumVars.WeighType.Weigh))
                {
                    if ((AppConstVars.mWeighMode == (int)GlobalEnumVars.WeighMode.ShowWeighForm) || (weight == 0))
                    {
                        frmFoodSpecWeigh foodSpecWeigh = new frmFoodSpecWeigh(ordering, foodspec);
                        foodSpecWeigh.Owner = form;
                        if (foodSpecWeigh.ShowDialog() == DialogResult.OK)
                        {
                            dQuantity = CommFunc.ConvertToDecimal(foodSpecWeigh.mScaleQty);
                        }
                        foodSpecWeigh.Dispose();
                    }
                    else dQuantity = weight;
                }
                #endregion
            }

            if (member != null) new MemberUtil().SetMemberPrice(ordering, member, foodspec);//执行会员价

            if (ordering.price == 0)
            {
                var frm = new frmDiscounts(ordering, (int)GlobalEnumVars.DiscountMode.ChangPrice);
                frm.lbl_caption.Text = ordering.name;
                if (frm.ShowDialog() == DialogResult.OK)
                {
                    var dicountInfo = frm.dicountInfo;
                    ordering.price = (decimal)((float)dicountInfo.Value);
                    ordering.realPrice = ordering.price;
                    ordering.discount = 1;
                }
                frm.Dispose();
                if (ordering.price == 0)
                {
                    msgStr = "";
                    return null;
                }
            }

            if (employee != null)
            {
                ordering.billerId = employee.id;
                ordering.parcel = employee.name;
            }
            ordering.orderId = orderingMaster.orderId;
            ordering.quantity = dQuantity;
            ordering.amount = ordering.price * dQuantity;
            ordering.realAmount = CommFunc.GetRowAmount(ordering.realPrice * dQuantity, AppConstVars.systemsetup.rowAmountDecimal);
            ordering.allAmount = CommFunc.GetRowAmount(ordering.realPrice * dQuantity, AppConstVars.systemsetup.rowAmountDecimal);

            if (food.type == (int)GlobalEnumVars.FoodType.PackFood)
            {
                ordering.isSelectSame = new corecmsfoodpackServices().IsAny(p => p.foodId == foodId && p.isSelectSame == true && p.isDelete == false);
                ordering.itemCount = 0;
            }
            
            //进行促销活动计算
            if (!new ActivitieUtil().SetOrderingPromotion(ordering, member, ref msgStr)) return null;//计算促销

            ordering.realAmount = CommFunc.GetRowAmount(ordering.realAmount, AppConstVars.systemsetup.rowAmountDecimal);
            ordering.allAmount = CommFunc.GetRowAmount(ordering.allAmount, AppConstVars.systemsetup.rowAmountDecimal);

            if (!new OrderingUtil().IsValidError(ordering)) return null;
            return ordering;
        }


        /// <summary>
        /// 根据商品类型ID查询类型名称
        /// </summary>
        /// <param name="custoType"></param>
        /// <returns></returns>
        public static corecmsfoodspec GetSpecByFoodCode(Form form, string code)
        {
            List<corecmsfoodspec> specList = new corecmsfoodspecServices().QueryByCode(code);
            if ((specList == null) || (specList.Count == 0)) 
            {                
                if (!form.ShowAskDialog("提示：", "所输入的商品不存在，要新增吗?", UIStyle.Red)) return null;
                if (!GetUserRoleAny(GlobalEnumVars.UserRoleType.addproduct, 0, false)) return null;
                frmFoodInfo frm = new frmFoodInfo(0, 0, code);
                frm.ShowDialog();
                frm.Dispose();
                specList = new corecmsfoodspecServices().QueryByCode(code);
                if ((specList == null) || (specList.Count == 0)) return null;
            }
            if (specList.Count == 1) return specList.FirstOrDefault();
            corecmsfoodspec foodspec = null;
            if (AppConstVars.systemsetup.orderingMode == (int)GlobalEnumVars.OrderingMode.Touch)
            {                
                var frm = new frmFoodSpecSelect(specList, null, true);
                if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    foodspec = frm.specModel;
                }
                frm.Dispose();                
            }
            else
            {
                var frm = new frmFoodSelect(specList);
                if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    foodspec = frm.specModel;
                }
                frm.Dispose();
            }

            return foodspec;
        }

        /// <summary>
        /// 获取临时商品
        /// </summary>
        /// <param name="custoType"></param>
        /// <returns></returns>
        public static corecmsfoodspec GetSpecByTempGoods(Form form)
        {
            if (!GetUserRole(GlobalEnumVars.UserRoleType.addproduct, 0)) return null;

            //var where = Expressionable.Create<corecmsfoodspec>();
            //where = where.And(a => a.isDelete == false);
            //where = where.And(a => a.spuTypeId == (int)GlobalEnumVars.GoodsSpuType.VirtualGoods);           

            //List<corecmsfoodspec> specList = new corecmsfoodspecServices().AsQueryable().WhereIF(true, where.ToExpression()).OrderBy(a => a.number).With(SqlWith.NoLock).ToList();

            var where = Expressionable.Create<corecmsfoodspec, corecmsfood>();
            where = where.And((f, s) => s.isDelete == false && s.sellStatus != 0 && f.onLine == true);
            where = where.And((f, s) => f.spuTypeId == (int)GlobalEnumVars.GoodsSpuType.VirtualGoods);

            int count = 0;
            List<corecmsfoodspec> specList = new corecmsfoodspecServices().QueryPageSpecAsync(ref count, 1, 200, where);

            if ((specList == null) || (specList.Count == 0))
            {
                if (!form.ShowAskDialog("提示：", "临时商品档案不存在，要新增吗?", UIStyle.Red)) return null;
                if (!GetUserRoleAny(GlobalEnumVars.UserRoleType.addproduct, 0, false)) return null;
                frmFoodInfo frm = new frmFoodInfo(0, 0, "", (int)GlobalEnumVars.GoodsSpuType.VirtualGoods);
                frm.ShowDialog();
                frm.Dispose();
                specList = new corecmsfoodspecServices().QueryPageSpecAsync(ref count, 1, 200, where);
                if ((specList == null) || (specList.Count == 0)) return null;
            }
            if (specList.Count == 1) return specList.FirstOrDefault();
            corecmsfoodspec foodspec = null;
            if (AppConstVars.systemsetup.orderingMode == (int)GlobalEnumVars.OrderingMode.Touch)
            {
                var frm = new frmFoodSpecSelect(specList, null, true);
                if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    foodspec = frm.specModel;
                }
                frm.Dispose();
            }
            else
            {
                var frm = new frmFoodSelect(specList);
                if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    foodspec = frm.specModel;
                }
                frm.Dispose();
            }

            return foodspec;
        }

        /// <summary>
        /// 根据商品类型ID查询类型名称
        /// </summary>
        /// <param name="custoType"></param>
        /// <returns></returns>
        public static corecmsfoodspec CreateSpecByFoodId(long id)
        {
            corecmsfood food = new corecmsfoodServices().GetSingle(a => a.id == id);
            if (food == null) return null;

            var specList = new corecmsfoodspecServices().AsQueryable().Where(p => p.foodId == food.id && p.isDelete == false).ToList();
            if ((specList == null) || (specList.Count == 0)) return null;

            var foodspec = specList.FirstOrDefault();
            if (specList.Count > 1)
            {
                foodspec = null;
                var frm = new frmFoodSpecSelect(specList, food);
                if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    foodspec = frm.specModel;
                    return foodspec;
                }
                frm.Dispose();
            }

            return foodspec;
        }

        #endregion

        /// <summary>
        /// 获取班次信息
        /// </summary>
        public static long GetClassData(long sysUserId)
        {
            AppConstVars.classNumber = "";
            AppConstVars.classId = 0;
            var classList = new corecmsfoodorderclassServices().AsQueryable()
                .Where(p => p.sysUserId == sysUserId && p.classOff == false).ToList();

            if ((classList == null) || (classList.Count == 0))
            {
                var frm = new frmClassOn();
                frm.ShowDialog();
                frm.Dispose();
            }
            else
            {
                var classinfo = classList.First();
                AppConstVars.classId = classinfo.id;
                AppConstVars.classNumber = classinfo.classNumber;
            }
            return AppConstVars.classId;
        }

        /// <summary>
        /// 获取系统参数配置
        /// </summary>
        public static void GetSystemSetup()
        {
            var systemsetup = new corecmssystemsetupService().SelectDataFirst();
            if (systemsetup == null)
            {
                systemsetup = new corecmssystemsetup();
                systemsetup.storeId = AppConstVars.sysUser.storeId;
                new corecmssystemsetupService().InsertOrUpdate(systemsetup);
                AppConstVars.systemsetup = new corecmssystemsetupService().SelectDataFirst();
            }
            else
            {
                AppConstVars.systemsetup = systemsetup;
            }
            AppConstVars.syssetting = new syssettingServices().GetById(AppConstVars.sysUser.corpId);
            if (AppConstVars.syssetting == null) AppConstVars.syssetting = new syssetting();
        }

        /// <summary>
        /// 获取登录用户的前台权限
        /// </summary>
        public static List<sysrolepos> GetUserRolePos(long sysUserId)
        {
            var userRoles = new sysroleposServices().AsQueryable().Where(p => p.sysUserId == sysUserId).ToList();            
            return userRoles;
        }

        /// <summary>
        /// 获取登录用户的前台权限
        /// </summary>
        public static sysroleinfo GetUserRoleInfo(long posRoleId)
        {

            var sysRoleInfo = new sysroleinfoServices().GetById(posRoleId);
            if (sysRoleInfo == null) sysRoleInfo = new sysroleinfo();
            return sysRoleInfo;
        }
    }
}
